 static boolean flag = true;

    public static boolean canFinish(int numCourses, int[][] prerequisites) {
//        for (int a = 0; a < numCourses; a++) {
        ArrayList<Integer> visited = new ArrayList<>();

        for (int i = 0; i < prerequisites.length; i++) {
            if(visited.indexOf(prerequisites[i][0])==-1) {
                visited.add(prerequisites[i][0]);
                ArrayList<Integer> list = new ArrayList<>();
                dfs(prerequisites[i][0], prerequisites, list);
                if (!flag) return false;
            }
        }
        return true;
    }

    public static void dfs(int x, int[][] prerequisites, ArrayList<Integer> list) {
        if (flag) {
            if (list.indexOf(x) != -1) {
                flag = false;
                return;
            }
            list.add(x);
            for (int i = 0; i < prerequisites.length; i++) {
                if (prerequisites[i][0] == x) {
                    dfs(prerequisites[i][1], prerequisites, list);
                }
            }
            list.remove(list.size() - 1);
        }
        return;
    }
